<template>
    <div class="uploadImg">
        <!-- 上传图片 -->
        <el-dialog class="uploadIMG" title="上传图片" :lock-scroll="true" :visible.sync="dialogVisible" :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false" center width="500px">
            <!-- 上传图片 -->
            <!-- el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload"></el-dialog> -->
            <el-upload
                v-if="dialogVisible"
                name="file"
                action="#"
                list-type="picture-card"
                :limit="1"
                :on-preview="preview"
                :on-success="onSuccess"
                :with-credentials="true"
                :on-error="uploadError"
                :before-upload="beforeUpload"
                :before-remove="handleRemove"
                :class="uploadShow ? 'disable' : ''"
                :http-request="requestUpload"
            >
                <i class="el-icon-plus"></i>
            </el-upload>
            <!-- <div v-if="form.status === 2 && !form.imgUrl && form.isOwner != 0">
                <el-image
                    style="height: 145px; height: 145px; border-radius: 10px"
                    :preview-src-list="[require('@/assets/images/gateway.png')]"
                    :src="require('@/assets/images/gateway.png')"
                    fit="cover"
                    v-if="form.deviceType == 2"
                ></el-image>
                <el-image
                    style="height: 145px; height: 145px; border-radius: 10px"
                    :preview-src-list="[require('@/assets/images/video.png')]"
                    :src="require('@/assets/images/video.png')"
                    fit="cover"
                    v-else-if="form.deviceType == 3"
                ></el-image>
                <el-image
                    style="height: 145px; height: 145px; border-radius: 10px"
                    :preview-src-list="[require('@/assets/images/product.png')]"
                    :src="require('@/assets/images/product.png')"
                    fit="cover"
                    v-else
                ></el-image>
            </div>
            <div v-else>
                <imageUpload ref="image-upload" :disabled="form.status === 2 ? true : false" :value="form.imgUrl" :limit="1" :fileSize="1" @input="getImagePath($event)"></imageUpload>
            </div> -->

            <!-- 按钮 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消 上 传</el-button>
                <el-button type="primary" @click="uploadImg">点 击 上 传</el-button>
            </span>
        </el-dialog>

        <!-- 图片放大 -->
        <el-dialog width="650px" :visible.sync="dialogVisibles" class="xianshi">
            <img draggable="false" style="width: 610px; margin: 20px 0px" :src="dialogImageUrl" alt="" />
        </el-dialog>
    </div>
</template>

<script>
import store from '@/store';
import { VueCropper } from 'vue-cropper';
import { uploadCOS } from '@/utils/upload';
import { uploadDragImg } from '@/api/iot/product';
import { mapActions } from 'vuex';

export default {
    name: 'uploadImg',
    components: { VueCropper },
    data() {
        return {
            dialogVisible: false, //弹框默认隐藏
            dialogVisibles: false, // 放大的图片
            dialogImageUrl: '', // 上传的图片
            uploadShow: false, //是否显示上传图片
        };
    },
    created() {},
    methods: {
        ...mapActions('dragEditor', ['setId', 'setPageSetup', 'setPageComponents', 'resetPageComponents']),
        /* 显示上传文件组件 */
        showUpload() {
            this.dialogVisible = true;
        },
        // 覆盖默认的上传行为
        requestUpload() {},
        // 上传预处理
        beforeUpload(file) {
            console.log(file);

            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => {
                this.dialogImageUrl = reader.result;
                console.log(this.dialogImageUrl);
            };
        },

        // 关闭弹框
        handleClose() {
            this.$confirm('点击取消后您填写的信息将丢失，您确定取消？')
                .then(() => {
                    this.handleRemove();
                    this.$emit('handleClose');
                    // 隐藏上传文件
                    this.dialogVisible = false;
                    this.dialogImageUrl = '';
                })
                .catch(() => {});
        },

        // 删除图片
        handleRemove() {
            this.uploadShow = false;
            this.dialogImageUrl = '';
            return true;
        },

        // 预览
        preview() {
            this.dialogVisibles = true;
        },

        // 上传成功
        onSuccess(response) {
            // 返回错误
            if (response.success != true) return this.$message.error('上传图片失败，请删除后重新上传');

            this.dialogImageUrl = response.data.src;
        },

        // 上传前
        uploads(file) {
            if (!file.type.includes('image')) {
                this.$message.error('请上传图片！');
                return false;
            }
            this.uploadShow = true;
        },

        // 上传失败
        uploadError() {
            this.$message.error('请重新上传');
            this.uploadShow = false;
        },

        /**
         * 自定义上传（使用腾讯云COS）
         * http-request	覆盖action默认的上传行为，可以自定义上传的实现
         * 如果要用api接口上传去除el-upload的 http-request属性即可
         */
        upload(data) {
            uploadCOS(data.file).then((res) => {
                this.dialogImageUrl = res;
            });
        },
        dataURLToBlob(dataURL) {
            // 分割 DataURL 的元数据和 Base64 内容
            const [metadata, base64] = dataURL.split(',');
            const mimeType = metadata.match(/:(.*?);/)[1];

            // 解码 Base64 字符串
            const byteCharacters = atob(base64);
            const byteArrays = [];

            // 分段处理二进制数据
            for (let offset = 0; offset < byteCharacters.length; offset += 512) {
                const slice = byteCharacters.slice(offset, offset + 512);
                const byteNumbers = new Array(slice.length);
                for (let i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                }
                byteArrays.push(new Uint8Array(byteNumbers));
            }

            return new Blob(byteArrays, { type: mimeType });
        },
        // 上传图片
        uploadImg() {
            let formData = new FormData();
            let img = this.dataURLToBlob(this.dialogImageUrl);
            formData.append('file', img);

            for (const [key, value] of formData.entries()) {
                console.log(key, value);
            }
            uploadDragImg(formData).then((response) => {
                // console.log('上传结果', response); // 去除开头的斜杠
                const dialogImageUrl = response.fileName.replace(/^\//, '');
                this.dialogImageUrl = process.env.VUE_APP_SERVER_API_URL + dialogImageUrl;
                // console.log('图片地址', this.dialogImageUrl);
                this.$modal.msgSuccess(this.$t('updateSuccess'));
                this.dialogVisible = false;
                this.setPageSetup({ ...this.$store.state.dragEditor.pageSetup, bgImg: this.dialogImageUrl });
                this.$emit('uploadInformation', this.dialogImageUrl);
            });
        },
    },
    computed: {
        // baseurl
        baseupload() {
            return `${window.global_config.BASE_URL}upload/miniShop`;
        },

        // 提交按钮是否可以点击
        disabl() {
            if (!this.dialogImageUrl) return true;
            return false;
        },
    },
};
</script>

<style lang="less" scoped>
@import '../../../assets/css/minx.less';
.uploadImg {
    // 上传弹框内容部分
    /deep/.uploadIMG .el-dialog__body {
        height: 280px;
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;
        justify-content: center;
    }

    .disable {
        /deep/.el-upload {
            display: none !important;
        }
    }
}
</style>
